package cn.yh.register.cmn.service.impl;

import cn.yh.register.cmn.listener.ExcelListener;
import cn.yh.register.cmn.mapper.DictMapper;
import cn.yh.register.cmn.service.DictService;
import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.model.cmn.Dict;
import cn.yh.register.vo.cmn.DictEeVo;
import com.alibaba.excel.EasyExcel;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 根据id查询子数据
     *
     * @param id 字典id
     * @return 子数据列表
     */
    @Override
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChildData(Long id) {
        List<Dict> dicts = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        for (Dict dict : dicts) {
            //处理hsaChildren属性
            dict.setHasChildren(this.hasChildren(dict.getId()));
        }
        return dicts;
    }

    /**
     * 导出数据
     *
     * @param response 响应对象 response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //文件
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("数据字典", "UTF-8");
            //设置响应头，告诉浏览器以附件的形式打开(下载)
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //获取数据
            List<Dict> dicts = baseMapper.selectList(null);
            ArrayList<DictEeVo> dictEeVos = new ArrayList<>();
            for (Dict dict : dicts) {
                DictEeVo vo = new DictEeVo();
                BeanUtils.copyProperties(dict,vo);
                dictEeVos.add(vo);
            }

            //写操作
            EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("数据字典").doWrite(dictEeVos);
        } catch (IOException e) {
            throw new RegisterException("数据导出失败",200001);
        }
    }

    /**
     * 导入数据
     * @param file 文件对象
     */
    @CacheEvict(value = "dict",allEntries = true)
    @Override
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new ExcelListener(baseMapper)).sheet("数据字典").doRead();
        } catch (IOException e) {
            throw new RegisterException("数据导入失败",200001);
        }
    }

    //查询某条数据是否有子节点
    private Boolean hasChildren(Long id) {
        Integer count = baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        return count > 0;
    }
}
